import { Reducer } from 'redux';
import { Effect } from 'dva';
import { message } from 'antd';
import {
  fetchUserTotalAsync,
  fetchComTotalAsync,
  fetchNoticeTotalAsync,
  fetchPolicyTotalAsync,
  fetchBusinessTotalAsync,
  fetchPolicyTopAsync,
  fetchPolicyTypeAsync,
  fetchNoticeTopAsync,
  fetchNoticeTypeAsync,
  fetchComInfopAsync,
  fetchVisitInfoAsync,
  fetchProjectListAsync,
  fetchProjectProgressListAsync,
  fetchUserAvatorAsync,
} from '@/services/homeIndex';

export interface HomeOverviewModelState {
  homeDataTotal?: object;
  visitDetail?: object;
  policyTop?: Array<object>;
  policyType?: Array<object>;
  noticeTop?: Array<object>;
  noticeType?: Array<object>;
  comInfopType?: Array<object>;
  comInfopArea?: Array<object>;
  visitInfo?: Array<object>;
  projectList?: Array<object>;
  projectProgressList?: Array<object>;
  userAvator?: object;
}

function getRateData(data: any[], valueKey = 'value') {
  let total = 0;
  for (let index = 0, len = data.length; index < len; index++) {
    const element = data[index];
    total += element[valueKey];
  }
  const newData = data.map(item => {
    item.rate = Number((item[valueKey] / total).toFixed(3));
    item.__percent = (item.rate * 100).toFixed(1);
    return item;
  });
  return newData;
}

export interface DataOverviewModelType {
  namespace: 'homeIndex';
  state: HomeOverviewModelState;
  effects: {
    queryDataTotal: Effect;
    queryPolicyTop: Effect;
    queryPolicyType: Effect;
    queryNoticeTop: Effect;
    queryNoticeType: Effect;
    queryComInfop: Effect;
    queryVisitInfo: Effect;
    queryProjectList: Effect;
    queryProjectProgressList: Effect;
    queryUserAvatorAsync: Effect;
  };
  reducers: {
    update: Reducer<HomeOverviewModelState>;
  };
}

const DataOverviewModel: DataOverviewModelType = {
  namespace: 'homeIndex',
  state: {
    homeDataTotal: {},
    userAvator: {},
    policyTop: [],
    policyType: [],
    noticeTop: [],
    noticeType: [],
    comInfopType: [],
    comInfopArea: [],
    visitInfo: [],
    visitDetail: {},
    projectList: [],
    projectProgressList: [],
  },
  effects: {
    *queryDataTotal({ payload }, { call, put }) {
      let userTotal = 0,
        comTotal = 0,
        businessTotal = 0;
      const { code: codeUser, data: dataUser } = yield call(fetchUserTotalAsync, payload);
      const { code: codeCom, data: dataCom } = yield call(fetchComTotalAsync, payload);
      const { code: codeNotice, data: dataNotice } = yield call(fetchNoticeTotalAsync, payload);
      const { code: codePolicy, data: dataPolicy } = yield call(fetchPolicyTotalAsync, payload);
      const { code: codeBus, data: dataBus } = yield call(fetchBusinessTotalAsync, payload);
      if (codeUser === '0') {
        userTotal = dataUser;
      }
      if (codeCom === '0') {
        comTotal = dataCom;
      }
      if (codeBus === '0') {
        businessTotal = dataBus;
      }
      const {
        totalNoticeApply = 0,
        totalNoticeCash = 0,
        totalPublishedNotice = 0,
        totalViews: noticeTotal = 0,
      } = dataNotice || {};
      const {
        totalEnterpriseMatch = 0,
        totalPersonalMatch = 0,
        totalPublishedPolicy = 0,
        totalViews: policyTotal = 0,
      } = dataPolicy || {};
      yield put({
        type: 'update',
        payload: {
          homeDataTotal: {
            userTotal,
            comTotal,
            businessTotal,
            totalPublishedNotice,
            noticeTotal,
            totalNoticeApply,
            totalNoticeCash,
            totalPublishedPolicy,
            policyTotal,
            totalEnterpriseMatch,
            totalPersonalMatch,
          },
        },
      });
    },

    *queryPolicyTop({ payload }, { call, put }) {
      const res = yield call(fetchPolicyTopAsync, payload);
      const { data = [] } = res;
      const policyTop = data;
      yield put({
        type: 'update',
        payload: {
          policyTop,
        },
      });
    },
    *queryPolicyType({ payload }, { call, put }) {
      const res = yield call(fetchPolicyTypeAsync, payload);
      const policyType = res.data || [];
      const newPolicyType = getRateData(policyType, 'count');
      yield put({
        type: 'update',
        payload: {
          policyType: newPolicyType,
        },
      });
    },
    *queryNoticeTop({ payload }, { call, put }) {
      const res = yield call(fetchNoticeTopAsync, payload);
      const { data = [] } = res;
      const noticeTop = data;
      yield put({
        type: 'update',
        payload: {
          noticeTop,
        },
      });
    },
    *queryNoticeType({ payload }, { call, put }) {
      const TYPE_DATA = {
        NORMAL_NOTICE: '普通公告',
        POLICY_DYNAMICS: '政策动态',
        APPLY_NOTICE: '申报公告',
        CASH_NOTICE: '兑现公告',
      };
      const res = yield call(fetchNoticeTypeAsync, payload);
      const { data = [] } = res;
      const noticeType = data.map(item => {
        item.cnName = TYPE_DATA[item.type];
        return item;
      });
      const newNoticeType = getRateData(noticeType, 'count');
      yield put({
        type: 'update',
        payload: {
          noticeType: newNoticeType,
        },
      });
    },
    *queryComInfop({ payload: { type = 1 } = {} }, { call, put }) {
      const res = yield call(fetchComInfopAsync, type);
      const result = type === 1 ? 'comInfopType' : 'comInfopArea';
      let data = res.data || [];
      if (type !== 1) {
        data = getRateData(data, 'count');
      }
      yield put({
        type: 'update',
        payload: {
          [result]: data,
        },
      });
    },
    *queryVisitInfo({ payload }, { call, put }) {
      const res = yield call(fetchVisitInfoAsync, payload);
      const { data = {} } = res;
      const { puvipMetrics = [], totalIP: ipCount = 0, totalPV: pv = 0, totalUV: uv = 0 } = data;
      const visitInfo = puvipMetrics.map(item => {
        item.stDate = item.stDate.substring(0, 10);
        return item;
      });
      yield put({
        type: 'update',
        payload: {
          visitInfo,
          visitDetail: { ipCount, pv, uv },
        },
      });
    },
    *queryProjectList({ payload }, { call, put }) {
      const res = yield call(fetchProjectListAsync, payload);
      let data = res.data || [];
      data = getRateData(data, 'value');

      yield put({
        type: 'update',
        payload: {
          projectList: data,
        },
      });
    },
    *queryProjectProgressList({ payload }, { call, put }) {
      const res = yield call(fetchProjectProgressListAsync, payload);
      const data = res.data || [];
      yield put({
        type: 'update',
        payload: {
          projectProgressList: data,
        },
      });
    },
    *queryUserAvatorAsync({ payload }, { call, put }) {
      const res = yield call(fetchUserAvatorAsync, payload);
      const { visit_uv = {} } = res.data;
      const { ages = [] } = visit_uv;
      const newAges = getRateData(ages);
      visit_uv.ages = newAges;
      yield put({
        type: 'update',
        payload: {
          userAvator: visit_uv,
        },
      });
    },
  },
  reducers: {
    update(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default DataOverviewModel;
